package com.zs.infrastructure.util.basic;

import com.zs.infrastructure.util.exception.ShareException;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @description: BigDecimal工具类
 * @author: wzc
 * @createDate: 2021/6/14 0:13
 */
public class BigDecimalUtil {

    private BigDecimalUtil() {}

    /**
     * 保留精度位数
     */
    private static final int SCALE_LENGTH = 2;

    /**
     * 加法运算
     * @param paramf
     * @param params
     * @return
     */
    public static BigDecimal add(BigDecimal paramf, BigDecimal params) {
        paramf = switchNullToZero(paramf);
        params = switchNullToZero(params);
        return paramf.add(params);
    }

    /**
     * 多参数加法运算
     * @param params
     * @return
     */
    public static BigDecimal adds(BigDecimal... params) {
        BigDecimal value = BigDecimal.ZERO;
        List<BigDecimal> list = Arrays.asList(params);
        for(BigDecimal b : list) {
            value = add(value,b);
        }
        return value;
    }

    /**
     * 减法运算
     * @param paramf
     * @param params
     * @return
     */
    public static BigDecimal subtract(BigDecimal paramf, BigDecimal params) {
        paramf = switchNullToZero(paramf);
        params = switchNullToZero(params);
        return paramf.subtract(params);
    }

    /**
     * 乘法运算
     * @param paramf
     * @param params
     * @return
     */
    public static BigDecimal multiply(BigDecimal paramf, BigDecimal params) {
        paramf = switchNullToZero(paramf);
        params = switchNullToZero(params);
        return paramf.multiply(params);
    }

    /**
     * 除法运算
     * @param paramf
     * @param params
     * @return
     */
    public static BigDecimal divide(BigDecimal paramf, BigDecimal params) {
        paramf = switchNullToZero(paramf);
        params = switchNullToZero(params);
        if (params.doubleValue() == 0) {
            throw new ShareException(1, "除数不能为零!");
        }
        return paramf.divide(params, SCALE_LENGTH, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * null情况下返回0
     * @param param
     * @return
     */
    public static BigDecimal switchNullToZero(BigDecimal param) {
        if (StringUtils.isEmpty(param)) {
            param = BigDecimal.ZERO;
        }
        return param;
    }

}
